package liaotianshi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 聊天室 服务器建立
 *      多人聊天，用了线程池
 */
public class ChatServer {
    private ServerSocket server;
    private Set<Socket> sockets;
    private  ExecutorService pool;

    public ChatServer() {
        try {
            sockets=new HashSet<>();
            pool=Executors.newCachedThreadPool();
            server=new ServerSocket(9899);
            while (true){
                Socket socket=server.accept();
                String cip=socket.getInetAddress().getHostAddress();
                sockets.add(socket);
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStreamReader isr=new InputStreamReader(socket.getInputStream());
                            BufferedReader br=new BufferedReader(isr);
                            PrintWriter out;
                            while (true){
                                String m=br.readLine();
                                for (Socket so:sockets){
                                    out=new PrintWriter(so.getOutputStream());
                                    out.write(cip+"说："+m+"\n");
                                    out.flush();
                                }
                            }
                        } catch (IOException e) {
                            //e.printStackTrace();//可能出现连接重置（reset）
                            sockets.remove(socket);
                        }
                    }
                });
            }
        } catch (IOException e) {
            //e.printStackTrace();
            System.out.println("端口被占用！");
        }
    }

    public static void main(String[] args){
        new ChatServer();
    }
}
